/*
███████╗██╗   ██╗ ██████╗██╗  ██╗
██╔════╝██║   ██║██╔════╝██║ ██╔╝
█████╗  ██║   ██║██║     █████╔╝ 
██╔══╝  ██║   ██║██║     ██╔═██╗ 
██║     ╚██████╔╝╚██████╗██║  ██╗
╚═╝      ╚═════╝  ╚═════╝╚═╝  ╚═╝
*/
package dao;

import common.JavaBean.EX_User;
import common.utils.DBUtilsV2;

import java.math.BigDecimal;
import java.sql.*;

public class EX_UserDao {

    /* —— 1. 插入备份 —— */
    public int insertUser(String username, String password, String phone,
                          Integer permission, String address, String email,
                          String description) throws SQLException {
        String sql = "{CALL sp_user_insert_backup(?, ?, ?, ?, ?, ?, ?, ?)}";
        try (Connection conn = DBUtilsV2.open();
             CallableStatement cs = conn.prepareCall(sql)) {
            cs.setString(1, username);
            cs.setString(2, password);
            cs.setString(3, phone);
            if (permission == null) cs.setNull(4, Types.INTEGER);
            else cs.setInt(4, permission);
            cs.setString(5, address);
            cs.setString(6, email);
            cs.setString(7, description);
            cs.registerOutParameter(8, Types.INTEGER);
            cs.execute();
            return cs.getInt(8); // 返回新 user_id
        }
    }

    /* —— 2. 多模态查询 —— */
    public ResultSet findUsers(Integer id, String usernameKeyword,
                               String phone, String email,
                               Integer permission) throws SQLException {
        String sql = "{CALL sp_user_find_multimode(?, ?, ?, ?, ?)}";
        Connection conn = DBUtilsV2.open();
        CallableStatement cs = conn.prepareCall(sql);
        if (id == null) cs.setNull(1, Types.INTEGER); else cs.setInt(1, id);
        cs.setString(2, usernameKeyword);
        cs.setString(3, phone);
        cs.setString(4, email);
        if (permission == null) cs.setNull(5, Types.INTEGER); else cs.setInt(5, permission);
        return cs.executeQuery(); // 调用方负责关闭
    }

    /* —— 3. 多模态修改 —— */
    public void updateUser(int id, String newPassword, String newPhone,
                           String newAddress, String newEmail,
                           String newDescription) throws SQLException {
        String sql = "{CALL sp_user_update_multimode(?, ?, ?, ?, ?, ?)}";
        try (Connection conn = DBUtilsV2.open();
             CallableStatement cs = conn.prepareCall(sql)) {
            cs.setInt(1, id);
            cs.setString(2, newPassword);
            cs.setString(3, newPhone);
            cs.setString(4, newAddress);
            cs.setString(5, newEmail);
            cs.setString(6, newDescription);
            cs.execute();
        }
    }
}
